<template>
  <div class="interview-chat">
    <div class="chat-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="chat-title">模拟面试</h1>
        </div>
      </div>
    </div>

    <div class="chat-container">
      <!-- 移除侧边栏，直接显示面试聊天界面 -->

      <div class="main-chat-area full-width">
        <div class="messages-container" ref="messagesContainer">
          <div v-if="messages.length === 0" class="welcome-message">
          </div>

          <ChatMessage
            v-for="message in messages"
            :key="message.id"
            :message="message.content"
            :is-user="message.isUser"
            :timestamp="message.timestamp"
          />

          <div v-if="isAiTyping" class="chat-message ai-message">
            <div class="message-avatar">
              <div class="avatar ai-avatar">AI</div>
            </div>
            <div class="message-content">
              <div class="message-bubble">
                <div class="ai-typing-content">
                  <div class="ai-response-text message-markdown" v-html="currentAiResponse"></div>
                  <LoadingDots v-if="isStreaming" />
                </div>
              </div>
            </div>
          </div>
        </div>

        <ChatInput
          :disabled="isAiTyping"
          @send-message="sendMessage"
          placeholder="请输入你的回答"
        />
      </div>
    </div>
  </div>
</template>

<script>
import ChatMessage from '@/components/ChatMessage.vue'
import ChatInput from '@/components/ChatInput.vue'
import LoadingDots from '@/components/LoadingDots.vue'
import { chatWithSSE, interviewWithSSE, getInterviewHistory, getSessionMessages, createInterview, deleteInterview, createChatSession, deleteChatSession, checkAndEvaluateInterview } from '@/api/aiChatApi.js'
import { isLoggedIn, getToken } from '@/utils/auth.js'
import { API_CONFIG, getApiUrl } from '@/api/config.js'

export default {
  name: 'InterviewChat',
  components: { ChatMessage, ChatInput, LoadingDots },
  data() {
    return {
      messages: [],
      isAiTyping: false,
      isStreaming: false,
      currentAiResponse: '',
      currentEventSource: null,
      isLoggedIn: false,
      selectedSessionId: null,
      interviewConfig: null
    }
  },
  computed: {
    maxRounds() {
      const c = (this.interviewConfig && this.interviewConfig.classicCount) || 0
      const p = (this.interviewConfig && this.interviewConfig.projectCount) || 0
      return c + p
    },
    currentRound() {
      return Math.floor(this.messages.length / 2)
    }
  },
  mounted() {
    this.isLoggedIn = isLoggedIn()
    if (this.isLoggedIn) {
      // 获取路由传递的面试配置
      this.getInterviewConfig()
      // 直接开始面试，不需要加载历史会话
      this.startInterview()
    }
  },
  methods: {
    getInterviewConfig() {
      // 从路由query中获取面试配置
      const configStr = this.$route.query.config
      if (configStr) {
        try {
          this.interviewConfig = JSON.parse(configStr)
          console.log('获取到面试配置:', this.interviewConfig)
        } catch (e) {
          console.error('解析面试配置失败:', e)
          // 使用默认配置
          this.interviewConfig = {
            interviewerType: 'normal',
            topics: ['java'],
            classicCount: 5,
            projectCount: 2
          }
        }
      } else {
        // 使用默认配置
        this.interviewConfig = {
          interviewerType: 'normal',
          topics: ['java'],
          classicCount: 5,
          projectCount: 2
        }
      }
    },
    formatInterviewType(title) {
      if (!title) return '面试';
      if (title.includes('压力')) return '压力面';
      if (title.includes('温柔')) return '温柔面';
      if (title.toLowerCase().includes('kpi')) return 'KPI面';
      return '普通面';
    },
    // 移除不再需要的方法
    // 移除不再需要的方法
    async startInterview() {
      try {
        console.log('开始创建面试会话...')
        // 创建面试会话，使用用户配置
        const r = await createInterview({ 
          interviewerType: this.getInterviewerTypeNumber(this.interviewConfig.interviewerType),
          interviewerTypeDesc: this.getInterviewerTypeDesc(this.interviewConfig.interviewerType),
          classicCount: this.interviewConfig.classicCount,
          projectCount: this.interviewConfig.projectCount,
          topics: this.interviewConfig.topics.join(',')
        })
        
        if (r && r.code === 200) {
          console.log('面试会话创建成功，开始面试')
          // 设置会话ID
          this.selectedSessionId = r.data.interviewId
          // 直接开始面试，由面试官开始发话
          await this.startAiResponse(null)
        } else {
          console.error('创建面试会话失败:', r)
        }
      } catch (e) {
        console.error('开始面试失败:', e)
      }
    },
    getInterviewerTypeNumber(type) {
      const typeMap = {
        'normal': 4,
        'pressure': 1,
        'gentle': 2,
        'kpi': 3
      }
      return typeMap[type] || 4
    },
    getInterviewerTypeDesc(type) {
      const descMap = {
        'normal': '普通面',
        'pressure': '压力面',
        'gentle': '温柔面',
        'kpi': 'KPI面'
      }
      return descMap[type] || '普通面'
    },
    // 移除不再需要的删除方法
    sendMessage(message) {
      if (this.isAiTyping || !this.selectedSessionId) {
        console.warn('AI正在回复或未选择会话，无法发送消息')
        return
      }
      
      console.log('发送用户消息:', message)
      this.addMessage(message, true)
      this.startAiResponse(message)
    },
    addMessage(content, isUser = false) {
      if (!content || content.trim() === '') return
      const message = {
        id: Date.now() + Math.random(),
        content: content.trim(),
        isUser,
        timestamp: new Date()
      }
      this.messages.push(message)
      this.scrollToBottom()
    },
    async startAiResponse(message) {
      if (!this.selectedSessionId) {
        console.warn('未选择会话，无法开始面试')
        return
      }
      
      this.isAiTyping = true
      this.isStreaming = true
      this.currentAiResponse = ''
      
      try {
        const payload = { 
          interviewSessionId: this.selectedSessionId
        }
        
        if (message && message.trim()) {
          payload.message = message
        }
        
        console.log('开始AI面试，payload:', payload)
        
        const es = await interviewWithSSE(payload,
          chunk => { 
            this.currentAiResponse += chunk; 
            // UI显示长度上限，避免过长
            const MAX_LEN = 1500
            if (this.currentAiResponse.length > MAX_LEN) {
              this.currentAiResponse = this.currentAiResponse.slice(0, MAX_LEN) + '…'
            }
            this.scrollToBottom() 
          },
          () => { 
            this.isAiTyping = false; 
            this.isStreaming = false 
          },
          () => { 
            this.isAiTyping = false; 
            this.isStreaming = false; 
            this.mergeStreamedMessage() 
            this.checkRoundAndMaybeEvaluate()
          }
        )
        this.currentEventSource = es
      } catch (e) {
        console.error('开始AI面试失败:', e)
        this.isAiTyping = false
        this.isStreaming = false
      }
    },
    // 收尾总结交由提示词触发，不在此处单独落库
    mergeStreamedMessage() {
      if (this.currentAiResponse && this.currentAiResponse.trim()) {
        this.addMessage(this.currentAiResponse, false)
        this.currentAiResponse = ''
      }
    },
    async checkRoundAndMaybeEvaluate() {
      try {
        if (!this.selectedSessionId) return
        // 当达到配置的总轮次后，触发评估并跳转
        if (this.currentRound >= this.maxRounds) {
          // 给结束语一点展示时间，避免用户感知突兀跳转
          await new Promise(resolve => setTimeout(resolve, 1200))
          const r = await checkAndEvaluateInterview(this.selectedSessionId)
          if (r && (r.code === 200 || r.code === 0)) {
            this.$router.push({ name: 'InterviewEvaluation', query: { sessionId: this.selectedSessionId } })
          }
        }
      } catch (e) {
        console.error('检查轮次或获取评估失败', e)
      }
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer
        if (container) container.scrollTop = container.scrollHeight
      })
    }
  }
}
</script>

<style scoped>
.interview-chat {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #010e50 url(@/assets/images/bg.jpg) center top no-repeat;
  background-size: 100% auto;
  color: #fff;
  overflow: hidden;
}

.chat-header { background: rgba(0, 35, 120, 0.8); border-bottom: 1px solid rgba(100, 162, 255, 0.3); backdrop-filter: blur(10px); }
.header-content { display: flex; align-items: center; justify-content: center; padding: 16px 20px; }
.title-section { text-align: center; }
.chat-title { font-size: 26px; font-weight: bold; letter-spacing: 2px; text-shadow: 2px 2px 4px rgba(0,0,0,.3); }
.chat-subtitle { font-size: 13px; color: rgba(255,255,255,.8); margin-top: 4px; }

.chat-container { flex: 1; display: flex; overflow: hidden; }

.main-chat-area { position: relative; flex: 1; display: flex; flex-direction: column; overflow: hidden; }
.main-chat-area.full-width { width: 100%; }
.messages-container { flex:1; overflow-y:auto; padding:20px 0; }
.welcome-message { display:flex; justify-content:center; align-items:center; height:100%; padding:0 20px; }
.welcome-content { text-align:center; max-width:500px; color: rgba(255,255,255,.9); background: rgba(0,35,120,.4); padding:40px; border-radius:20px; border: 1px solid rgba(100,162,255,.3); backdrop-filter: blur(10px); }

.chat-message { display:flex; margin-bottom:20px; padding:0 20px; }
.ai-message { justify-content:flex-start; flex-direction:row; }
.message-avatar { display:flex; align-items:flex-start; margin:0 10px; }
.avatar { width:40px; height:40px; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:14px; font-weight:bold; color:white; border:2px solid rgba(100,162,255,.3); backdrop-filter: blur(5px); }
.ai-avatar { background: linear-gradient(135deg, #6c757d, #8a9ba8); box-shadow: 0 2px 8px rgba(108,117,125,.3); }
.message-content { max-width:70%; min-width:100px; }
.message-bubble { padding:12px 16px; border-radius:18px; position:relative; word-wrap: break-word; word-break: break-word; background: rgba(0,35,120,.6); color:#fff; border-bottom-left-radius:4px; backdrop-filter: blur(10px); border:1px solid rgba(100,162,255,.2); box-shadow: 0 4px 12px rgba(0,35,120,.2); }
.ai-typing-content { display:flex; flex-direction:column; gap:8px; }
.ai-response-text { font-size:14px; line-height:1.5; }

@media (max-width: 768px) {
  .chat-container { flex-direction: column; }
}
</style>

 